{% extends "base.html" %}

{% block content %}

{% if not embedded %}
{% include "navbar.html" %}
{% end %}

<div class="container" id="fishlog">
<div class="row">
	<div class="col-md-12">
		<div class="text-center" v-show="!loaded">
			<h3><i class="glyphicon glyphicon-refresh"></i> Loading ...</h3>
		</div>
		{% if not embedded %}
		<div class="text-center" v-show="(loaded && start_id != 0)">
			<span class="btn btn-success" @click="fetchMore">Load More</span>
		</div>
		{% end %}
		<ul id="logs" v-show="loaded">
			<li class="row" data-id="{{!msg.id}}" v-for="msg in msgs" track-by="id">
				<span class="nickname col-xs-6 nick-color-{{!msg.sender|colorNum}}">{{!msg.sender}}</span>
				<span class="time col-xs-6 text-right">{{!msg.time}}</span>
				<span class="col-xs-12">
					<span class="content" data-msg-type="{{!msg.mtype}}">
						<span v-if="!(hideContent[msg.mtype])">{{{! msg.content | fishify }}}</span>
						<img v-if="(msg.mtype=='photo'||msg.mtype=='sticker')" class="thumbnail fishroom-{{!msg.mtype}}" src='' :src="msg.media_url" @load="imgLoaded" />
						<audio v-if="msg.mtype=='audio'" class="fishroom-audio" controls><source src='' :src="msg.media_url" /></audio>
						<video v-if="msg.mtype=='animation'" class="fishroom-video fishroom-animation" autoplay loop muted><source src='' :src="msg.media_url" /></video>
						<video v-if="msg.mtype=='video'" class="fishroom-video" controls><source src='' :src="msg.media_url" /></video>
					</span>
				</span>
				<span class="msg-channel col-xs-12 text-right">
					via {{!msg.channel}}
				</span>
			</li>
		</ul>
	</div>
</div>
</div>

<div id="chatbar">
	<div class="container">
		{% if fishroom.config.config.get("bindings", {}).get(room, {}).get("web_post", True) %}
		<div class="join-chat" v-show="!nickname">
			<form class="form-inline" @submit="setNickname">
				<div class="form-group">
					<label for="my-nickname">Nickname</label>
					<input type="text" class="form-control" v-model="nickname_i"/>
				</div>
				<span class="btn btn-primary" @click="setNickname" :disabled="nickname_i==''"> Join Chat </span>
			</form>
		</div>
		<div class="send-text" v-show="nickname">
			<form @submit="sendFishMsg">
				<div class="form-group">
					<label class="sr-only" for="my-msg-text"></label>
					<div class="input-group">
						<span class="input-group-addon">{{!nickname}}</span>
						<input type="text" class="form-control" v-model="msg_text" />
					</div>
				</div>
				<span class="btn btn-primary" @click="sendFishMsg" :disabled="(coolDown||msg_text=='')"> Send </span>
				<a href="https://img.vim-cn.com/" target=":blank" @click="addImagePrefix" class="btn btn-default" > Picture </a>
				<span class="btn btn-default" @click="unsetNickname" > Reset Nickname </span>
			</form>
		</div>
		{% end %}
		{% if not embedded %}
		<div id="footer">
				<div class="text-center">
					<span>Powered by <a href="https://github.com/tuna/fishroom">Fishroom</a> </span>| <span>Licensed under GPLv3</span>
					{% if 'sponsor' in fishroom.config.config %} <span class="hidden-xs"> | <span>{% raw fishroom.config.config['sponsor']['footer'] %}</span> </span>{% end %}
				</div>
		</div>
		{% end %}
	</div>
</div>

{% end %}

{% block js %}
<script src="//cdn.bootcss.com/blueimp-md5/1.1.1/js/md5.min.js"></script>

<script>
$(document).ready(function() {
	var getColorNum = function() {
		var cache = {};
		function getColorNum_(str) {
			if (cache[str]) {
				return cache[str];
			}
			var frag = parseInt(md5(str).substr(0, 8), 16);
			return frag & 0x0f;
		}
		return getColorNum_;
	}();
	
	Vue.filter('colorNum', function(text){
		return getColorNum(text);
	});
	
	Vue.filter('fishify', function(text){
		var urlRegex = /(https?:\/\/[^\s]+)/g;
		return emojione.toImage(
				text
						.replace(/</g, '&lt;')
						.replace(/>/g, '&gt;')
						.replace(/"/g, '&quot;')
						.replace(/(?:\r\n|\r|\n)/g, '<br/>')
						.replace(urlRegex, '<a href="$1">$1</a>')
		);
	});
	
	window.shouldScroll = true;
	var fishLogData = {
		start_id: -1,
		current_id: {{next_id}},
		fetchLimit: 10,
		loaded: false,
		msgs: [],
		hideContent: {'photo': true,'sticker': true, 'animation': true, 'audio': true, 'video': true}
	}
	window.new_message = function(msg) {
		msg.id = fishLogData.current_id;
		fishLogData.current_id++;
		fishLogData.msgs.push(msg);
	}
	
	var fetchLog = function(limit, lastId, scrollDown) {
		var here = document.location.toString().split('?')[0];
		limit = typeof limit !== 'undefined' ? limit : 10;
		scrollDown = typeof scrollDown !== 'undefined' ? scrollDown : true;
		
		var params = {'json': 1, 'limit': limit};
		if(typeof lastId !== 'undefined') {
			params['last'] = lastId;
		}
		params = $.param(params);
		var url = here + '?' + params;
		console.log(url);
		$.ajax({
			url: url,
			type: "GET",
			dataType: "json"
		}).done(function(msgs){
			fishLogData.loaded = true;
			fishLogData.msgs = msgs.concat(fishLogData.msgs);
			if(msgs.length > 0) {
				fishLogData.start_id = msgs[0].id;
			}
			if(scrollDown) {
				setTimeout(function(){
						window.scrollTo(0, document.body.scrollHeight)
				}, 300);
			} else {
				window.shouldScroll = false;
			}
		});
	}

	var fishLogVue = new Vue({
		el: "#fishlog",
		data: fishLogData,
		ready: function() {
			var limit = 64;
			if (document.location.search) {
				var query = location.search.substr(1);
				query.split('&').forEach(function(part){
					var item = part.split('=');
					if (item[0]=="limit") {
						limit = parseInt(item[1]);
					}
				});
			}
			fetchLog(limit);
		},
		methods: {
			fetchMore: function() {
				fetchLog(42, this.start_id, false);
			},
			imgLoaded: function() {
				// console.log("img loaded");
				if (window.shouldScroll) {
						window.scrollTo(0, document.body.scrollHeight);
				}
			}
		}
	});
	
	{% if enable_ws %}
	window.CreateWebSocket = function() {
		var scheme=document.location.protocol.replace(/^http/g, 'ws'), 
				host=document.location.host,
				wsurl = scheme + '//' + host + '{{basepath}}/msg_stream';
				ws = new WebSocket(wsurl);

		ws.onopen = function() {
			ws.send('{"room": "{{room}}"}');
		};

		ws.onmessage = function(ev) {
			if (ev.data == "OK") {
				console.log("OK");
			} else {
				var msg = JSON.parse(ev.data);
				// console.log(msg);
				new_message(msg);
				var b = document.body, d = document.documentElement;
				if(b.scrollHeight - (d.scrollTop + d.clientHeight) < 500) {
					// console.log(b.scrollHeight - (d.scrollTop + d.clientHeight));
					window.shouldScroll = true;
					window.scrollTo(0, document.body.scrollHeight);
				} else {
					window.shouldScroll = false;
				}
			}
		};
		ws.onclose = function(ev) {
			console.log("socket closed, try reconnecting");
			setTimeout(function(){
				CreateWebSocket();
			}, 5*1000);
		};
	};
	
	CreateWebSocket();
	{% end %}
	
	{# chatbar #}
	// $("#chatbar").css("width", $(".container>.row").width()+"px");
	
	var chatData = {
		nickname: localStorage.getItem("nickname"),
		nickname_i: "",
		msg_text: "",
		coolDown: false
	}
	var chatVue = new Vue({
		el: "#chatbar",
		data: chatData,
		methods: {
			setNickname: function(ev){
				ev.preventDefault();
				if (! this.nickname_i) {
					return;
				}
				this.nickname = this.nickname_i;
				this.nickname_i = "";
				localStorage.setItem("nickname", this.nickname);
			},
			unsetNickname: function(ev) {
				this.nickname = "";
				ev.preventDefault();
			},
			addImagePrefix: function() {
				if (this.msg_text == "") {
					this.msg_text = "/imglink ";	
				}
			},
			sendFishMsg: function(ev){
				if (this.coolDown || this.msg_text == '') {
					return;
				}
				chatData.coolDown = true;
				var data = {nickname: this.nickname, content: this.msg_text};
				$.ajax({
					type: "POST",
					url: "{{basepath}}/messages/{{room}}/",
					data: JSON.stringify(data),
					dataType: 'json'
				}).done(function(msg) {
					chatData.msg_text = "";
				}).fail(function(xhr) {
					if (xhr.status == 400) {
						alert(xhr.responseJSON.msg);
					}
				}).always(function(){
					setTimeout(function(){
						chatData.coolDown = false;
					}, 500);
				});
				ev.preventDefault();
			}
		}
	});

});
</script>
{% end %}

{% block css %}
<style>
.container {
	max-width: 800px;
}
{% if not embedded %}
#fishlog {
	padding-top: 80px;
}
{% end %}
ul#logs {
	font-size: 14px;
	list-style-type: none;
	font-family: monospace;
	padding-left: 0;
	margin-bottom: 240px;
}
ul#logs > li {
	padding-top: 7px;
	padding-bottom: 7px;
	line-height: 1.33;
	border-top: 1px solid #EEE;
}
ul#logs > li:hover {
	background-color: #fafafa;
}
ul#logs > li:first-child {
	border-top: none;
}
ul#logs > li > span.time {
	color: #888;
}
ul#logs > li > span.msg-channel {
	color: #888;
	font-size: .9em;
}
ul#logs > li span.content {
	font-family: 'Source Han Sans CN', 'WenQuanYi Zen Hei', 'WenQuanYi Micro Hei', 'Heiti SC', 'Hiragino Sans GB', 'STHeiti', '微软雅黑', sans-serif;
	min-height: 20px;
}
ul#logs > li img.thumbnail {
	margin-top: 5px;
	max-height: 300px;
	max-width: 100%;
}
ul#logs > li audio.fishroom-audio, ul#logs > li video.fishroom-video  {
	margin-top: 5px;
}
ul#logs > li img.thumbnail.fishroom-sticker {
	max-width: 200px;
	border: none;
}
{% include nickcolors.css %}
#footer {
	height: 30px;
}
#footer img {
	max-height: 30px;
}

#titlebar {
	position: fixed;
	top: 0;
	width: 100%;
	background: white;
	z-index: 1000;
}
#titlebar > .container {
	border-bottom: solid 1px #eee;
}
#chatbar {
	position: fixed;
	bottom: 0;
	height: 130px;
	background: white;
	width: 100%;
}
#chatbar > .container {
	padding-top: 15px;
	border-top: solid 1px #eee;
}
</style>

{% end %}
{#
vim: ts=2 sts=2 sw=2 noexpandtab
#}
